package file

import (
	"blog/app/model/file"
	fileModel "blog/app/model/file"
	fileRequest "blog/app/request/file"
	fileResource "blog/app/resource/file"
	file2 "blog/app/services/condition/file"
	"blog/core"
	"blog/utils/upload"
	"fmt"

	"golang.org/x/exp/slices"
)

// 获得配置
func (rev File) GetFileConfig() []fileResource.ConfigLists {
	var lists []fileResource.ConfigLists
	core.DbConnect.Model(fileModel.Config{}).Find(&lists)
	return lists
}

// GetLists 获得列表
func (rev File) GetLists(param fileRequest.FileLists) (*[]fileResource.FileLists, int64) {
	fmt.Println(param)
	var lists []fileResource.FileLists
	field := []string{"id", "hash", "url", "Fid"}
	var count int64
	core.DbConnect.Model(fileModel.File{}).Count(&count).Order("update_time DESC").Limit(param.Limit).Offset((param.Page - 1) * param.Limit).Select(field).Find(&lists)
	var fid = make([]int, 0)
	for _, v := range lists {
		if !slices.Contains(fid, v.Fid) {
			fid = append(fid, v.Fid)
		}
	}

	var config []file.Config
	core.DbConnect.Model(file.Config{}).Where("id in (?)", fid).Find(&config)
	configIds := make(map[int]*file.Config)
	for _, v := range config {
		configIds[v.ID] = &v
	}

	for i := 0; i < len(lists); i++ {
		prefix := ""
		if _, ok := configIds[lists[i].Fid]; ok {
			prefix = "https://" + configIds[lists[i].Fid].Domain + "/"
		}

		lists[i].Url = prefix + lists[i].Url
	}
	return &lists, count
}

func (rev File) Upload(file upload.File, IsLocal bool) (fileModel.CreateFile, error) {
	var info fileModel.Config
	core.DbConnect.Model(fileModel.Config{}).Where("name = ?", "qiniu").Find(&info)
	ret, err := upload.Client(info.Name).SetBucket(info.Bucket).SetKey(info.Ak, info.As).Upload(file)

	if err != nil {
		return fileModel.CreateFile{}, err
	}

	originUrl := ""
	if IsLocal == false {
		originUrl = file.GetFileName()
	}

	option := file.GetOption()
	create := fileModel.CreateFile{
		Hash:      ret.Hash,
		Url:       ret.Path,
		Fid:       info.ID,
		Name:      option.FileName,
		Type:      option.MineType,
		OriginUrl: originUrl,
	}

	err = core.DbConnect.Create(&create).Error

	if err != nil {
		return fileModel.CreateFile{}, err
	}

	create.Domain = info.Domain
	create.IsHttps = int(info.IsHttps)

	return create, nil
}

// GetInfoHash 根据hash获得详情
func (rev *File) GetInfoHash(hash string) (*fileModel.File, error) {
	var info fileModel.File
	return &info, core.DbConnect.Model(rev.fileModel).Scopes(file2.SelectHash(hash)).Find(&info).Error
}

func (rev *File) ExistsHash(hash string) bool {
	var count int64
	core.DbConnect.Model(rev.fileModel).Scopes(file2.SelectHash(hash)).Count(&count)
	return count > 0
}

// Create 添加记录
func (rev *File) Create(param *file.CreateFile) error {
	return core.DbConnect.Create(&param).Error
}
